extends CharacterBody2D

@onready var chatWatch=$Chat
@onready var ani=$AnimatedSprite2D
@onready var timer=$Timer
@onready var talk=$对话
@onready var task=$任务

# npc执行策略
enum {
    IDLE,
    MOVE,
    NEW_DIR,
}

var speed:=30
var dir=Vector2.RIGHT
var state='空闲'
var action=NEW_DIR
var chatting=false 

var player:Player

func _ready() -> void:
    pass

func  _physics_process(delta: float) -> void:
    ai(delta)
    ani.play(state)

func ai(delta):
    state='空闲'
    match action:
        IDLE:
            pass
        MOVE:
            move(delta)
        NEW_DIR:
            dir=rand([Vector2.LEFT,Vector2.RIGHT,Vector2.UP,Vector2.DOWN])
    if Input.is_action_just_pressed('交互') and player:chat()
    if Input.is_action_just_pressed('任务') and player:getTask()

func chat():
    if chatting:return
    chatting=true
    talk.start()

func getTask():
    if chatting:return
    chatting=true
    task.newTask()

func move(delta):
    if chatting:return
    if dir.x==-1:state='向左走'
    if dir.x==1:state='向右走'
    if dir.y==-1:state='向上走'
    if dir.y==1:state='向下走'
    position+=dir*speed*delta

func rand(arr:Array):
    arr.shuffle()
    return arr.front()

# ----------------------信号-----------------------#
# 玩家进入可交互区域
func _on_chat_body_entered(body:Node2D) -> void:
    if body is Player:player=body

func _on_chat_body_exited(body:Node2D) -> void:
    if body is Player:player=null
# npc策略循环
func _on_timer_timeout() -> void:
    timer.wait_time=rand([0.5,1.0,1.5])
    action=rand([IDLE,MOVE,NEW_DIR])

# 聊天关闭
func _on_talk_over() -> void:
    chatting=false
# 任务关闭
func _on_task_closed() -> void:
    chatting=false

func _on_玩家_collect_item(item:String) -> void:
    if item=='木棍':task.stick+=1
